package me.zhengjie.modules.hanzi.rest;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.hanzi.service.StrokeService;
import me.zhengjie.utils.Result;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/strokes")
@RequiredArgsConstructor
public class StrokesController {
    private final StrokeService strokeService;
    
    @GetMapping("/gif/{character}")
    public Result<Map<String, Object>> getStrokeGif(@PathVariable String character) {
        try {
            Map<String, Object> data = strokeService.getStrokeGif(character);
            return Result.ok(data);
        } catch (Exception e) {
            // 详细的错误日志
            log.error("获取汉字 {} 的笔顺数据失败", character, e);
            return Result.error("获取汉字 " + character + " 笔顺数据失败: " + e.getMessage());
        }
    }

    @GetMapping("/debug/{character}")
    public Result<Map<String, Object>> debugStrokeGif(@PathVariable String character) {
        Map<String, Object> debugInfo = new HashMap<>();
        try {
            // 直接调用百度API不经过缓存
            String url = String.format("https://hanyuapp.baidu.com/dictapp/word/detail_getworddetail?wd=%s&client=pc&lesson_from=xiaodu&smp_names=wordNewData1", character);
            debugInfo.put("requestUrl", url);
            
            Map apiResponse = strokeService.restTemplate.getForObject(url, Map.class);
            debugInfo.put("apiResponse", apiResponse);
            debugInfo.put("success", true);
            
            return Result.ok(debugInfo);
        } catch (Exception e) {
            debugInfo.put("success", false);
            debugInfo.put("error", e.getMessage());
            debugInfo.put("errorType", e.getClass().getSimpleName());
            return Result.error("调试信息获取失败: " + e.getMessage());
        }
    }

    @GetMapping("/image/{character}/{strokeNumber}")
    public Result getStrokeImage(@PathVariable String character, @PathVariable Integer strokeNumber) {
        try {
            String base64Image = strokeService.getStrokeImg(character,strokeNumber);
            return Result.ok(base64Image);
        } catch (Exception e) {
            return Result.error("获取汉字 " + character + " 笔顺图像失败: " + e.getMessage());
        }
    }
}
